package com.pactera.chatRoom.controller;

import java.security.Principal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.pactera.chatRoom.entity.ChatMsg;
import com.pactera.chatRoom.service.MessageServcie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

/*
* 如何实现把消息放入kafka
* 不直接把消息发送给目标用户
* 先给发送端所在服务器的生产者  
* 然后由目标用户所在的服务器上的生产者接受消息 最后给到目标用户
* */

@Controller
public class ChatController {
	@Autowired
	SimpMessagingTemplate template;

	@Autowired
	MessageServcie msgService;
	
	@MessageMapping("/chat")
    public void chat(Principal principal, ChatMsg msg) throws Exception {
        String from=principal.getName();
        msg.setFroMan(from);
        
		Calendar calendar = Calendar.getInstance();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date date = calendar.getTime();
		
		msg.setTime(df.format(date));//添加发送时间

		msgService.saveMsg(msg);//保存聊天消息

        template.convertAndSendToUser(msg.getToMan(), "/queue/chat", msg);;
    }

}
